package com.itheima.controller;


import cn.itheima.health.entity.QueryPageBean;
import cn.itheima.health.entity.Result;
import cn.itheima.health.service.UserAdminService;
import com.itheima.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.Callable;

@RestController
@RequestMapping("/userAdmin")
public class UserAdminController {

    @Reference
    private UserAdminService userAdminService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/findPage.do")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        try {
            Map map = userAdminService.findPage(queryPageBean);
            return new Result(true, "用户信息查询成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"用户信息查询失败");
        }
    }

    @RequestMapping("/add.do")
    public Result add(@RequestBody User user,@RequestParam("roleIds")Integer[] roleIds){
        try {
            String password = user.getPassword();
            user.setPassword(bCryptPasswordEncoder.encode(password));
            userAdminService.add(user,roleIds);
            return new Result(true,"新增用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"新增用户失败");
        }
    }

    @RequestMapping("/edit.do")
    public Result edit(@RequestBody User user,@RequestParam("roleIds") Integer[] roleIds){
        try {
            String password = user.getPassword();
            user.setPassword(bCryptPasswordEncoder.encode(password));
            userAdminService.edit(user,roleIds);
            return new Result(true,"编辑用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"编辑用户失败");
        }
    }

    @RequestMapping("/deleteUserAdminById.do")
    public Result deleteUserAdminById(@RequestParam("id") Integer id){
        try {
            userAdminService.deleteUserAdminById(id);
            return new Result(true,"删除用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"删除用户失败");
        }
    }
}
